package com.face.controller;

import com.face.service.AccountService;
import com.face.service.UserService;
import com.face.util.WechatContact;
import com.face.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class PushController {

    @Autowired
    UserService userService;

    @Autowired
    AccountService accountService;

    @Value("${wechat.templateid}")
    String templateId;

    @Value("${wechat.aimUrl}")
    private String aimUrl;

    private static final String[] postList = {"touser", "template_id", "data"};
    private static final String[] dataList = {"first", "keyword1", "keyword2", "keyword3", "keyword4", "remark"};
    private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 推送消息
     *
     * @param userId
     * @return MAP<String, Object>(结果json)
     */
    @RequestMapping("/push")
    public List<Object> push(@RequestParam("userId") String userId) {

        UserWrapper userWrapper = userService.findByUserId(userId);
        RestTemplate restTemplate = new RestTemplate();

        Map<String, Object> postData = getPostData(userWrapper, getActionMap(userId));//getActionMap()方法根据参数判断选择推送的是Url还是小程序页面
        Object result=null;
        if (userWrapper.getOpenId()!=null) {
            result = restTemplate.postForEntity(WechatContact.getTemplateURL(), postData, HashMap.class).getBody();//模板消息
        }
        List<Object> list = new ArrayList<>();
        list.add(result);
        return pushToManager(list, postData, userWrapper);
    }

    /**
     * 判断是否推送给超级管理员并进行操作
     *
     * @param list
     * @param postData
     * @param userWrapper
     * @return
     */
    private List<Object> pushToManager(List<Object> list, Map<String, Object> postData, UserWrapper userWrapper) {

        RestTemplate restTemplate = new RestTemplate();
        List<String> openidList = accountService.findEnableNotifyOpenids(userWrapper.getShopId());
        for (String openid : openidList) {
            if (!openid.equals(userWrapper.getOpenId())) {
                postData.put("touser", openid);
                Object manageResult = restTemplate.postForEntity(WechatContact.getTemplateURL(), postData, HashMap.class).getBody();
                list.add(manageResult);
            }
        }
        return list;
    }

    /**
     * 获取推送url的Map对象
     *
     * @param userId
     * @return
     */
    private Map<String, Object> getActionMap(String userId) {

        Map<String, Object> map = new HashMap<>();
        map.put("url", this.aimUrl + userId);
        return map;
    }

    /**
     * 获取推送小程序页面的Map对象
     *
     * @param appId
     * @param pagepath
     * @return
     */
    private Map<String, Object> getActionMap(String appId, String pagepath) {

        Map<String, Object> map = new HashMap<>();

        Map<String, Object> miniprogram = new HashMap<>();
        miniprogram.put("appid", appId);
        miniprogram.put("pagepath", pagepath);

        map.put("miniprogram", miniprogram);
        return map;
    }

    /**
     * 获取推送的数据的Map对象
     *
     * @param userWrapper
     * @param actionMap
     * @return
     */
    private Map<String, Object> getPostData(UserWrapper userWrapper, Map<String, Object> actionMap) {

        Map<String, Object> postData = new HashMap<>();
        Object[] list = {userWrapper.getOpenId(), templateId, null};
        list[2] = getModelDataMap(userWrapper.getUsername(), WechatContact.getPushRemark(userWrapper.getType(), userWrapper.getGroup(), df.format(userWrapper.getUpdateTime()), userWrapper.getVisitCount()));

        for (int i = 0; postList.length == list.length && i < list.length; i++) {
            postData.put(postList[i], list[i]);
        }
        postData.putAll(actionMap);
        return postData;
    }

    /**
     * 获取推送数据中模板消息的相关信息的Map对象
     *
     * @param username
     * @param remark
     * @return
     */
    private Map<String, Object> getModelDataMap(String username, String remark) {

        String[] list = {WechatContact.PUSH_HEADER, df.format(System.currentTimeMillis()), username, "无", "无", remark};

        Map<String, Object> map = new HashMap<>();
        for (int i = 0; dataList.length == list.length && i < list.length; i++) {
            Map<String, Object> value = new HashMap<>();
            value.put("value", list[i]);
            map.put(dataList[i], value);
        }
        return map;
    }

}


